package com.hspedu.newData.dmsxl.图;
/**
 * @Author: yh
 * @description: 
 * @CreateTime: 2025-05-28 
 * @Version: 1.0
 */

//todo
public class LC1905统计子岛屿 {

    private int[][] dir = new int[][]{{0,1},{1,0},{0,-1},{-1,0}};
    boolean flag = true;
    public int countSubIslands(int[][] grid1, int[][] grid2) {

        int m = grid1.length;
        int n = grid1[0].length;

        boolean[][] visited = new boolean[m][n];
        int res = 0;

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid2[i][j]==1){
                    dfs(grid1,grid2,i,j);
                    if (flag){
                        res++;
                    }
                    flag = true;
                }
            }
        }

        return res;
    }
    public void dfs(int[][] grid1,int[][] grid2,int x,int y){
        if (x<0||y<0||x>= grid1.length||y>=grid1[0].length){
            return;
        }
        if (grid2[x][y]!=1) return;
        if (grid1[x][y]!=1) {
            flag = false;
            return;
        }
        grid2[x][y] = 2;
        for (int i = 0; i < 4; i++) {
            int nextX = x + dir[i][0];
            int nextY = y + dir[i][1];
            dfs(grid1,grid2,nextX,nextY);
        }

    }
}

